package Linux五种IO模型.reactor2;


import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author coderFu
 * @create 2022/3/8
 * 完成客户端数据的读操作
 */
public class ReadState implements HandlerState{

    private SelectionKey sk;

    @Override
    public void changeState(HandlerDemo2 h) {

    }

    @Override
    public void handle(HandlerDemo2 h, SelectionKey sk, SocketChannel sc, ThreadPoolExecutor pool) throws IOException {

        this.sk = sk;
        // 非阻塞模式下，不可以使用Readers 因为Readers不支持 non-blocking

        byte[] array = new byte[1024];

        ByteBuffer buffer = ByteBuffer.wrap(array);

        // 将数据写入到 缓冲区中

        int write = sc.write(buffer);

        if (write == -1){

            System.out.println("客户端已经关闭");
            // 关闭管道的方法
            h.closeChannel();
            return;
        }

        // 将写入的数据 转换为 字符串
        String requestMessage = new String(array);

        if (! "".equals(requestMessage)){
            // 如果数据不为空
            h.setState(new WorkState());
            pool.execute(new WorkThread(h,requestMessage));
            System.out.println("客户端发送来的数据为："+sc.socket().getRemoteSocketAddress().toString());

        }
    }



    class WorkThread implements Runnable{
        HandlerDemo2 h;
        String str;
        public WorkThread(HandlerDemo2 h, String str){
            this.h = h;
            this.str = str;
        }

        @Override
        public void run() {
            process(h,str);
        }

    }

   // 保证多线程的安全性

    synchronized void process(HandlerDemo2 h, String str){
        // 处理相关的业务逻辑内容
        // 改变工作状态

        this.sk.interestOps(SelectionKey.OP_WRITE);
        this.sk.selector().wakeup(); // 是一个阻塞的selector 立刻返回
    }




}


